﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Module.Interfaces.Common;
using System.Web;
using System.Web.Caching;

namespace Core.Module.Common
{
    public class CacheManager:ICacheManager
    {
        public T Get<T>(string key, ActionWithResult<T> executeIfNoFound, int minutesToCache)            
        {
            Cache cache=EnsureCache();
            T result = (T)cache.Get(key);
            if (result != null) return result;
            result = executeIfNoFound.Invoke();
            return Set<T>(key, result, minutesToCache);
        }

        private Cache EnsureCache()
        {
            return HttpContext.Current.Cache;
        }

        public T Set<T>(string key, T data, int minutesToCacheFor)
        {
            Cache cache = EnsureCache();
            cache.Add(key, data, null, DateTime.Now.AddMinutes(minutesToCacheFor), Cache.NoSlidingExpiration, CacheItemPriority.Normal, (a,b,c) => { });
            return data;
        }

        public void Remove(string key)
        {
            Cache cache = EnsureCache();
            cache.Remove(key);
        }
    }
}
